#!/usr/bin/python

# offset_template.py

from __future__ import division

import sys
from optparse import OptionParser

from ot_simulator.template import template_funs

def write_template(radius, filename_in, fileout, work_on_right, reversed):
    template_in = template_funs.file_multi_num(filename_in)
    if reversed:
        template_in = reverse(template_in)
        template_out = reverse(template_funs.offset_template(radius,
                                                             template_in,
                                                             work_on_right))
    else:
        template_out = template_funs.offset_template(radius, template_in,
                                                     work_on_right)
    for x, y, orig_x in template_out:
        print >> fileout, "{0:.4f},{1:.4f},{2:.4f}".format(x, y, orig_x)

def reverse(it):
    r'''Reverses the elements in sequence ``it``.

        >>> tuple(reverse((1,2,3)))
        (3, 2, 1)
    '''
    t = tuple(it)
    for i in range(len(t) - 1, -1, -1):
        #print >> sys.stderr, "reverse yielding:", t[i]
        yield t[i]

def run():
    parser = \
      OptionParser(
        usage="usage: %prog [options] tool_radius template_in [template_out]",
        version= '%prog 0.1.0')
    parser.add_option("-l", "--left",
                      action="store_false", dest="work_on_right",
                      default=True, help="work is to left of tool")
    parser.add_option("-r", "--reversed", action="store_true", dest="reversed",
                      default=False,
                      help="process input template in reverse order")

    (options, args) = parser.parse_args()

    if len(args) < 2 or len(args) > 3:
        parser.error("incorrect number of arguments")

    radius = float(args[0])

    if len(args) == 2:
        write_template(radius, args[1], sys.stdout, options.work_on_right,
                       options.reversed)
    else:
        with open(args[2], 'wt') as fileout:
            write_template(radius, args[1], fileout, options.work_on_right,
                           options.reversed)

if __name__ == "__main__":
    run()

